<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>数据发送示例</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.7.2/css/all.min.css" rel="stylesheet">
</head>

<body class="bg-gray-100 font-sans">
    <div class="container mx-auto p-8">
        <h1 class="text-3xl font-bold mb-4">发送数据到后端</h1>
        <form id="dataForm" class="space-y-4">
            <div>
                <label for="name" class="block text-sm font-medium text-gray-700">姓名</label>
                <input type="text" id="name" class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm">
            </div>
            <div>
                <label for="age" class="block text-sm font-medium text-gray-700">年龄</label>
                <input type="number" id="age" class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm">
            </div>
            <button type="submit" class="w-full flex justify-center py-2 px-4 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500">
                发送数据
            </button>
        </form>
        <div id="response" class="mt-4 p-4 bg-white border border-gray-300 rounded-md"></div>
    </div>
    <script>
        document.getElementById('dataForm').addEventListener('submit', function (e) {
            e.preventDefault();
            const name = document.getElementById('name').value;
            const age = document.getElementById('age').value;
            const data = {
                name: name,
                age: age
            };
            fetch('data/', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': '{{ csrf_token }}'
                },
                body: JSON.stringify(data)
            })
              .then(response => response.json())
              .then(result => {
                    const responseDiv = document.getElementById('response');
                    responseDiv.innerHTML = `<pre>${JSON.stringify(result, null, 2)}</pre>`;
                })
              .catch(error => {
                    const responseDiv = document.getElementById('response');
                    responseDiv.innerHTML = `<pre>错误: ${error.message}</pre>`;
                });
        });
    </script>
</body>

</html>
